<template>
  <div class="practice-modal-container">
    <el-dialog v-model="myVisible" class="task-modal" :show-close="false">
      <template #header>
        <div class="my-header flex-center">
          布置{{ props.taskType === 2 ? '习题任务' : '错题任务' }}
          <img
            src="@/assets/images/common/close.png"
            class="close-btn hover"
            @click="onclose"
          />
        </div>
      </template>
      <el-form
        class="practice-form"
        :model="form"
        ref="formRef"
        :rules="rules"
        label-width="auto"
      >
        <el-form-item
          v-if="props.taskType === 4"
          label="题目推送范围："
          required
          prop="rangeTime"
        >
          <el-date-picker
            v-model="form.rangeTime"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item
          v-if="props.taskType === 4"
          label="科目："
          required
          prop="subjectId"
        >
          <el-select v-model="form.subjectId" placeholder="请选择科目">
            <el-option
              v-for="item in subjectList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="接收班级：" required prop="classList">
          <span v-if="!classList.length">请选择科目</span>
          <el-checkbox-group
            v-model="form.classList"
            @change="changeSelectClass"
          >
            <el-checkbox
              :value="item"
              name="type"
              v-for="(item, index) in classList"
              :key="index"
            >
              {{ item.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item
          v-if="props.taskType === 4"
          label="题目推送："
          required
          prop="topicSource"
        >
          <el-checkbox-group v-model="form.topicSource">
            <template class="flex">
              <el-checkbox value="1" size="large" name="push">
                <div></div>
                推送
                <el-input-number
                  v-model="form.sourceCount"
                  :min="1"
                  :max="10"
                  @click.prevent
                />

                原错题
              </el-checkbox>
            </template>

            <el-checkbox value="2" size="large" name="push">
              推送
              <el-input-number
                v-model="form.similarCount"
                :min="1"
                :max="3"
                @click.prevent
              />相似题
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item
          v-if="props.taskType === 2"
          label="已选题目："
          required
          prop="questionList"
        >
          {{ form.questionList.length }}道
        </el-form-item>
        <el-form-item label="作业标题：" required prop="title">
          <el-input v-model="form.title" placeholder="请输入作业标题" />
        </el-form-item>
        <el-form-item label="发布时间：" required prop="publishTime">
          <el-date-picker
            :disabled-date="commonDateDisable"
            v-model="form.publishTime"
            type="datetime"
            placeholder="立即发布"
          />
        </el-form-item>
        <el-form-item label="截止时间：" required prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            :disabled-date="commonDateDisable"
            @change="onChangeEndTime"
            type="datetime"
            placeholder="请选择截止时间"
            style="width: 1.2rem"
          />
        </el-form-item>
        <el-form-item label="错题重练：" prop="wrongReturn">
          <el-switch v-model="form.wrongReturn" />
        </el-form-item>
        <div class="flex return-box" v-if="form.wrongReturn">
          <el-form-item
            label="重练方式"
            required
            prop="returnType"
            label-position="top"
          >
            <el-select
              v-model="form.returnType"
              placeholder="请选择重练方式"
              style="width: 1.2rem"
            >
              <el-option
                v-for="item in returnTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="重练时间"
            required
            prop="returnTime"
            label-position="top"
          >
            <el-date-picker
              @change="onChangeReturn"
              :disabled-date="disabledDate"
              :disabled-hours="disabledHour"
              :disabled-minutes="disabledMinute"
              :disabled-seconds="disabledSecond"
              v-model="form.returnTime"
              type="datetime"
              style="width: 1.2rem"
              placeholder="请选择你重练时间"
            />
          </el-form-item>
          <el-form-item
            label="重练题型"
            required
            prop="returnQuesType"
            label-position="top"
          >
            <el-select
              v-model="form.returnQuesType"
              placeholder="请选择重练题型"
              style="width: 1.2rem"
            >
              <el-option
                v-for="item in returnQUesTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="作业描述：">
          <el-input
            type="textarea"
            v-model="form.desc"
            placeholder="请输入作业描述"
          />
        </el-form-item>
        <el-form-item label="上传附件：">
          <el-upload
            style="width: 100%"
            :auto-upload="false"
            :on-change="customUpload"
            :show-file-list="false"
            accept=".xls,.xlsx,.pdf,.txt,.ppt,.pptx,.doc,.docx"
          >
            <el-button style="margin-top: 0.04rem" link type="primary">
              点击上传附件
            </el-button>
          </el-upload>
          <div class="flex file-box">
            <div
              class="file-item"
              v-for="(file, index) in form.file"
              :key="index"
            >
              <img
                src="@/assets/images/assignment/delete.png"
                @click="onDeleteFile(index)"
                class="hover close-img"
                alt=""
              />
              <img class="file-img" :src="getFileImg(file.name)" />
            </div>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="myVisible = false" class="cancel-btn"
            >取消</el-button
          >
          <el-button
            type="primary"
            :disabled="isSubmit"
            v-throttle="5000"
            @click="onConfirm(formRef)"
            class="confirm-btn"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref } from 'vue'
import { useTaskStore, useAuthStore } from '@/stores'
import { storeToRefs } from 'pinia'
import dayjs from 'dayjs'
import { uploadFile, getFileImg, beforeUpload } from '@/utils/upload'
import { ElMessage, ElLoading } from 'element-plus'
import {
  postPracticeTask,
  postSubmitWrongTopic,
  postCollect
} from '@/apis/assignment/index'
import { subjectMap } from '@/constants/subject-map'
import router from '@/router'
import { useRoute } from 'vue-router'
import {
  returnTypeOptions,
  returnQUesTypeOptions,
  commonDateDisable
} from '@/views/assignment/util'

const props = defineProps({
  visible: {
    default: false,
    type: Boolean
  },
  // 2习题任务，4错题任务
  taskType: {
    type: Number
  }
})

const emit = defineEmits(['update:visible'])
const myVisible = computed({
  get() {
    return props.visible
  },
  set(value) {
    emit('update:visible', value)
  }
})
const route = useRoute()
const authStore = useAuthStore()
const { userInfo } = storeToRefs(authStore)
const useTask = useTaskStore()
const taskStore = storeToRefs(useTask)
const originClassList = ref([])
const subjectList = ref([])
const isSubmit = ref(false)

const formRef = ref()
const form = ref({
  rangeTime: [],
  subjectId: null,
  classList: [],
  topicSource: ['1'],
  sourceCount: 1,
  similarCount: 1,
  questionList: [],
  title: '',
  publishTime: null,
  endTime: dayjs().add(3, 'day').endOf('day'),
  desc: '',
  file: [],
  wrongReturn: false,
  returnType: 1, // 重练方式
  returnTime: dayjs()
    .add(4, 'day')
    .set('hour', 7)
    .set('minute', 0)
    .set('second', 0), // 重练时间
  returnQuesType: 0 // 重练题型
})

const rules = ref({
  subjectId: [{ required: true, message: '请选择科目', trigger: 'change' }],
  topicSource: [
    {
      type: 'array',
      required: true,
      message: '请选择题目推送',
      trigger: 'change'
    }
  ],
  rangeTime: [
    {
      type: 'array',
      required: true,
      message: '请选择题目推送范围',
      trigger: 'change'
    }
  ],
  publishTime: [
    {
      required: true,
      validator: (_, value, callback) => {
        callback()
      },
      trigger: 'change'
    }
  ],
  returnTime: [
    { required: true, message: '请选择重练时间', trigger: 'change' }
  ],
  questionList: [
    { type: 'array', required: true, message: '请选择习题', trigger: 'change' }
  ],
  classList: [
    { type: 'array', required: true, message: '请选择班级', trigger: 'change' }
  ],
  title: [{ required: true, message: '请输入标题', trigger: 'change' }],
  endTime: [{ required: true, message: '请输入截止时间', trigger: 'change' }]
})

const changeSelectClass = param => {
  let str = param.map(item => item.label).join(',') + ' '
  str += props.taskType === 2 ? subjectMap[taskStore.subjectId.value] : ''
  form.value.title =
    str +
    (props.taskType === 2 ? '习题任务' : '错题任务') +
    dayjs().format(' YYYY-MM-DD')
}

// 上传文件
const customUpload = async file => {
  // console.log('1111111111111', file, document.getElementsByClassName('el-upload__input')[0].value);
  // file.localPath = document.getElementsByClassName('el-upload__input')[0].value
  let isContinue = beforeUpload(file)
  if (!isContinue) {
    return
  }
  if (form.value.file.length > 5) {
    ElMessage.info('已达到上传上限')
    return
  }
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.3)'
  })
  const res = await uploadFile(file)
  loading.close()
  form.value.file.push(res)
}

const onDeleteFile = index => {
  form.value.file.splice(index, 1)
}

// 检查表单数据
const validateForm = async ruleForm => {
  return await ruleForm.validate(valid => {
    if (valid) {
      return true
    } else {
      return false
    }
  })
}
// 提交表单
const onConfirm = async ruleForm => {
  if (!(await validateForm(ruleForm))) return
  if (props.taskType === 2) {
    await postPracticeTaskFun()
  } else if (props.taskType === 4) {
    await postSubmitWrongTopicInfo()
  }
}

/**
 * 提交错题数据
 */
const postSubmitWrongTopicInfo = async () => {
  const param = {
    class_info: form.value.classList.map(item => ({
      class_name: item.label,
      class_id: Number(item.value),
      class_type: item.class_type,
      layer_id: []
    })),
    original_incorrect_question: {
      tag: form.value.topicSource.indexOf('1') !== -1 ? 1 : 0,
      count: form.value.sourceCount
    },
    similar_question: {
      tag: form.value.topicSource.indexOf('2') !== -1 ? 1 : 0,
      count: form.value.similarCount
    },
    start_time: dayjs(form.value.rangeTime[0]).startOf('day').unix(),
    end_time: dayjs(form.value.rangeTime[1]).endOf('day').unix(),
    task_type: 4,
    topic_source: Number(form.value.topicSource),
    homework_title: form.value.title,
    homework_description: form.value.desc,
    create_time: form.value.publishTime
      ? dayjs(form.value.publishTime).startOf('day').unix()
      : dayjs().startOf('day').unix(),
    deadline: dayjs(form.value.endTime).endOf('day').unix(),
    annex: form.value.file.map(item => ({
      url: item.url,
      name: item.name
    })),
    release: 1,
    teacher_id: Number(userInfo.value.userId),
    teacher_name: userInfo.value.userName,
    school_id: Number(userInfo.value.school_id),
    discipline: form.value.subjectId,
    task_classification: 2,
    wrong_question: {
      tag: Number(form.value.wrongReturn)
    }
  }
  // 开启错题处理
  if (param.wrong_question.tag) {
    param.wrong_question = {
      ...param.wrong_question,
      retrain_time: dayjs(form.value.returnTime).unix(),
      train_method: form.value.returnType,
      wrong_question_type: form.value.returnQuesType
    }
  }
  isSubmit.value = true
  const res = await postSubmitWrongTopic(param)
  isSubmit.value = false

  if (res.code === 1) {
    ElMessage.success('错题任务发布成功')

    // 数据埋点
    postCollect({
      action_type: 2,
      task_id: res.data.task
    })

    const query = {
      taskId: res.data.task,
      name: param.homework_title,
      classList: JSON.stringify(param.class_info),
      taskType: props.taskType,
      fileList: JSON.stringify(param.annex)
    }
    console.log('传递数据', query)
    onclose()
    router.push({
      name: 'practiceDetail',
      query
    })
  }
}

/**
 * 提交习题任务
 */
const postPracticeTaskFun = async () => {
  const param = {
    topic: form.value.questionList,
    class_info: form.value.classList.map(item => ({
      class_name: item.label,
      class_id: Number(item.value),
      class_type: item.class_type,
      layer_id: []
    })),

    task_type: 2,
    homework_title: form.value.title,
    homework_description: form.value.desc,
    create_time: form.value.publishTime
      ? dayjs(form.value.publishTime).startOf('day').unix()
      : dayjs().startOf('day').unix(),
    deadline: dayjs(form.value.endTime).endOf('day').unix(),
    annex: form.value.file.map(item => ({
      url: item.url,
      name: item.name
    })),
    release: 1,
    teacher_id: Number(userInfo.value.userId),
    teacher_name: userInfo.value.userName,
    school_id: Number(userInfo.value.school_id),
    discipline: taskStore.subjectId.value,
    task_classification: 1,
    wrong_question: {
      tag: Number(form.value.wrongReturn)
    }
  }
  if (route.path.includes('target-boost')) {
    param.task_classification = 2
  }
  // 开启错题处理
  if (param.wrong_question.tag) {
    param.wrong_question = {
      ...param.wrong_question,
      retrain_time: dayjs(form.value.returnTime).unix(),
      train_method: form.value.returnType,
      wrong_question_type: form.value.returnQuesType
    }
  }
  const res = await postPracticeTask(param)

  if (res.code === 1) {
    ElMessage.success('习题任务发布成功')

    // 数据埋点
    postCollect({
      action_type: 2,
      task_id: res.data.task
    })

    const query = {
      taskId: res.data.task,
      courseId: 0
    }
    useTask.reset()
    console.log('传递数据', query)
    onclose()
    router.push({
      name: 'courseDetail',
      query
    })
  }
}

const onclose = () => {
  emit('update:visible', false)
}

const classList = computed(() => {
  if (props.taskType === 2) {
    return originClassList.value
  } else {
    return originClassList.value.filter(
      item => Array.from(item.subjectList).indexOf(form.value.subjectId) !== -1
    )
  }
})

const initData = async () => {
  const res = await authStore.getUserInfoFun()
  originClassList.value = res.classList
  subjectList.value = res.subjectList
  form.value.questionList = taskStore.taskList.value
  changeSelectClass([])
}

// 控制重练时间和截止时间
const onChangeReturn = param => {
  if (dayjs(param).valueOf() <= dayjs(form.value.endTime).valueOf()) {
    form.value.returnTime = dayjs(form.value.endTime).valueOf() + 1000
  }
}

const onChangeEndTime = param => {
  form.value.returnTime = dayjs(param)
    .add(1, 'day')
    .set('hour', 7)
    .set('minute', 0)
    .set('second', 0)
}

const disabledDate = time => {
  return time.getTime() <= dayjs(form.value.endTime).add(-1, 'day').valueOf()
}
const disabledHour = () => {
  if (
    form.value.endTime &&
    dayjs(form.value.returnTime).format('YYYY-MM-DD') ==
      dayjs(form.value.endTime).format('YYYY-MM-DD')
  ) {
    let disabled = []
    for (let i = 0; i < dayjs(form.value.endTime).hour(); i++) {
      disabled.push(i)
    }
    return disabled
  } else {
    return []
  }
}
const disabledMinute = () => {
  if (
    form.value.endTime &&
    dayjs(form.value.returnTime).format('YYYY-MM-DD HH') ==
      dayjs(form.value.endTime).format('YYYY-MM-DD HH')
  ) {
    let disabled = []
    for (let i = 0; i < dayjs(form.value.endTime).minute(); i++) {
      disabled.push(i)
    }
    return disabled
  } else {
    return []
  }
}
const disabledSecond = () => {
  if (
    form.value.endTime &&
    dayjs(form.value.returnTime).format('YYYY-MM-DD HH:mm') ==
      dayjs(form.value.endTime).format('YYYY-MM-DD HH:mm')
  ) {
    let disabled = []
    for (let i = 0; i < dayjs(form.value.endTime).second() + 1; i++) {
      disabled.push(i)
    }
    return disabled
  } else {
    return []
  }
}

initData()
</script>

<!-- eslint-disable -->
<style lang="less">
.practice-modal-container {
  .my-header {
    position: relative;
    font-size: 18px;
    font-weight: bold;

    .close-btn {
      position: absolute;
      right: 0;
      font-size: 22px;
    }
  }

  .practice-form {
    overflow-y: auto;
    max-height: 66vh;
    padding-right: 30px;
    .return-box {
      gap: 20px;
      margin-bottom: 10px;
    }

    /* stylelint-disable ebag/selector-class-pattern */
    .el-form-item__label,
    .el-checkbox {
      height: 40px;
      line-height: 40px;
    }

    .el-select__wrapper {
      font-size: 20px;
    }

    .setting-icon {
      margin-left: 20px;
      font-size: 20px;
    }

    .file-box {
      flex-wrap: wrap;
      gap: 20px;

      .file-item {
        position: relative;
        width: 44px;
        height: 44px;

        .close-img {
          position: absolute;
          right: 0;
          top: 0;
          width: 14px;
          height: 14px;
          transform: translate(50%, -50%);
          display: none;
        }

        &:hover {
          .close-img {
            display: block;
          }
        }

        .file-img {
          width: 44px;
          height: 44px;
        }
      }
    }
  }

  .el-dialog {
    width: 700px;
    border-radius: 24px;
    padding: 40px;
    margin-top: 6vh !important;
  }
}
</style>
